<?php
/**
*
* 功能描述（订单控制器）
*
* @author suoya <jlusuoya@gmail.com>
* @version 1
*/

class CtrlOrder extends CtrlBase
{
	public $paramCheck = array(
		"commit" => array(
			"cart" => array("SESSION", "must", "", ""),
		),
		'modmsg' => array(
			'id' => array('GET', 'must', 'intval', 'positive'),
			'msg' => array('POST', 'must', 'trim', ''),
		),
		'modpaytype' => array(
			'id' => array('GET', 'must', 'intval', 'positive'),
			'pay_type' => array('POST', 'must', 'intval', 'positive'),
		),
		"create" => array(
			"need_card_birthday" => array("POST", "must", "intval", "bool"),
			"card_birthday" => array("POST", "", "trim", ""),
			"need_card" => array("POST", "must", "intval", "bool"),
			"card_message" => array("POST", "", "trim", "notempty"),
			"need_album" => array("POST", "must", "intval", "bool"),
			"need_candle" => array("POST", "must", "intval", "bool"),
			"true_area" => array("POST", "must", "trim", "notempty"),
			"true_address" => array("POST", "must", "trim", "notempty"),
			"true_consignee" => array("POST", "must", "trim", "notempty"),
			"true_zipcode" => array("POST", "0", "intval", "notnegative"),
			"true_mobile_to" => array("POST", "must", "trim", "notempty"),
			"true_mobile_from" => array("POST", "must", "trim", "notempty"),
			"true_sign_building" => array("POST", "", "trim", ""),
			"true_delivery_type" => array("POST", "must", "trim", "notempty"),
			"dely_date" => array("POST", "must", "", "date"),
			"dely_time" => array("POST", "must", "", "timeslot"),
			"payment" => array("POST", "must", "intval", "positive"),
			"card_pwd" => array("POST", "", "trim", "notempty"),	//代金
			"integral" => array("POST", "0", "intval", "notnegative"), //积分
			"need_inv" => array("POST", "0", "intval", "bool"),
			"inv_payee" => array("POST", "", "trim", ""),
			"inv_content" => array("POST", "", "trim", ""),
			"postscript" => array("POST", "", "trim", ""),
			"cart" => array("SESSION", "must", "", ""),
			"order_set" => array("SESSION", "must", "", ""),
		),
		"detail" => array(
			"id" => array("GET", "must", "intval", "positive"),
		),
		"pay" => array(
			"id" => array("GET", "must", "intval", "positive"),
		),
		"cancel" => array(
			"id" => array("GET", "must", "intval", "positive"),
		),
		"showlist" => array(
			"page" => array("GET", "1", "intval", "positive"),
		),
		"addcomment" => array(
			"id" => array("GET", "must", "intval", "positive"),
			"whole" => array("POST", "must", "intval", "notnegative"),
			"taste" => array("POST", "must", "intval", "notnegative"),
			"service" => array("POST", "must", "intval", "notnegative"),
			"comment" => array("POST", "must", "trim", "notempty"),
		),
	);

	public $perms = array(
		"commit" => array(1, 255, "index.php?action=user.tologin"),
		"create" => array(1, 255, "index.php?action=user.tologin"),
		"detail" => array(1, 255, "index.php?action=user.tologin"),
		"cancel" => array(1, 255, "index.php?action=user.tologin"),
		"showlist" => array(1, 255, "index.php?action=user.tologin"),
		"addcomment" => array(1, 255, "index.php?action=user.tologin"),
		"pay" => array(1, 255, "index.php?action=user.tologin"),
		"modmsg" => array(1, 255, "index.php?action=user.tologin"),
	);

	function ModMsg()
	{
		$obj = $this->GetModel("order");
		$cnt = $obj->Update(array('message' => $this->params['msg']), $this->params['id'], $this->user->userid);
		if($cnt > 0)
			echo '0';
		else
			echo '2';
		return RT_NONE;
	}

	function ModPayType()
	{
		$obj = $this->GetModel("order");
		$p_type = $this->params['pay_type'];
		//{#$p_type=[ 1=>'余额支付', 2=>'货到付款', 3=>'支付宝在线支付', 4=>'银行转账', 11=>'月结(VIP会员)', 12=>'周结(VIP会员)', 21=>'赠送(内部专用)']#}
		if(!in_array($p_type, array(1, 3, 4, 11, 12)))
			return RT_ATTACK;
		$id = $this->params['id'];
		$mod_data = array('pay_type' => $p_type);
		if($p_type == 1)
		{
			$odata = $obj->GetBaseInfo($id, $this->user->userid);
			if(!$odata)
			{
				echo '该订单不再需要付款';
				return RT_NONE;
			}
			$uobj = $this->GetModel("user");
			$udata = $uobj->GetAccInfo($this->user->userid);
			if($udata['money'] < $odata['amount'])
			{
				echo '余额不足，仅有'.$udata['money'];
				return RT_NONE;
			}
			if(!$uobj->DecMoney($this->user->userid, $odata['amount']))
			{
				echo '扣款失败';
				return RT_NONE;
			}
			$mod_data['pay_adm'] = 1;
		}
		$cnt = $obj->Update($mod_data, $this->params['id'], $this->user->userid, 'and pay_adm = 0');
		if($cnt > 0)
			echo '0';
		else
			echo '2';
		return RT_NONE;
	}

	function ShowList()
	{
		$obj = $this->GetModel("order");
		$data = $obj->GetList($this->user->userid, $this->params['page']);
		$goods = array();
		foreach($data['data'] as $item)
		{
			$id = $item['id'];
			$good = $obj->GetGoods($id);
			$goods[$id] = $good;
		}
		$this->assign("goods", $goods);
		$this->assign("orderlist", $data['data']);
		$this->assign("totalCnt", $data['cnt']);
		$this->assign("pageCnt", $data['pageCnt']);
		$this->assign("curPage", $this->params['page']);
		return RT_TPL;
	}

	function Detail()
	{
		$obj = $this->GetModel("order");
		$id = $this->params['id'];
		$data = $obj->GetDetail($id, $this->user->userid);
		if(!$data)
		{
			$this->assign("msg", "订单不存在");
			return RT_MSG;
		}
		$good = $obj->GetGoods($id);
		$this->assign("goods", $good);
		$this->assign("order", $data);
		return RT_TPL;
	}

	function Cancel()
	{
		$this->assign("msg", "禁用");
		return RT_MSG;
	}

	function Commit()
	{
		if($this->user->usertype == 2 && $this->user->level == 1)
		{
			$this->assign("msg", "您申请的团体会员尚未审批，无法下订单。审批之后，重新登录生效。");
			return RT_MSG;
		}

		$obj = $this->GetModel("user");
		$data = $obj->GetAccInfo($this->user->userid);
		$this->assign('user_acc', $data);
		$obj = $this->GetModel("Address");
		$data = $obj->GetList($this->user->userid);
		$this->assign("userAddress", $data);

		$ctrl = $this->GetCtrl("Cart");
		$ctrl->SELF_ReloadData();
		$_SESSION['order_set'] = time(0);	//标记确认过
		
		$cart = $_SESSION['cart'];
		$cnt = 0;
		$score = 0;
		$amount = $this->GetAmount($cart, $cnt, $score);
		$this->assign('c_score', $score);
		if($cnt != count($cart))
		{
			$this->assign('msg', '部分商品已过期，请修改购物车之后再下单');
			return RT_MSG;
		}
		$this->assign("cartlist", $cart);
		$this->assign("amount", $amount);
		$this->assign("mobile", $this->user->mobile);
		$this->assign("u_level", $this->user->level);
		$this->assign("u_type", $this->user->usertype);
		$this->assign("area_come", AREA_COME);
		$this->assign("addr_come", ADDR_COME);
		return RT_TPL;
	}

	function Pay()
	{
		$obj = $this->GetModel("Order");
		$data = $obj->GetBaseInfo($this->params['id'], $this->user->userid);
		if(!$data)
		{
			$this->assign("msg", NO_ORDER);
			return RT_MSG;
		}
		$p_type =array(
			1=>'余额支付', 2=>'货到付款', 3=>'支付宝在线支付',
			4=>'银行转账', 5=>'银联在线支付', 11=>'月结(VIP会员)',
			12=>'周结(VIP会员)', 21=>'赠送(内部专用)');
		$type = intval($data['pay_type']);
		switch($type)
		{
		case 3: 	//支付宝
			global $web_root;
			$amount = $data['amount'];
			$amount = 0.01;		//suya 测试代码
			$data = array(
				'trade_type' => 2,
				'type' => $type,
				'amount' => $amount,
				'id' => $data['id'],
				'user_id' => $this->user->userid,
				'info' => '订单'.(ORDERBASE+$data['id']).$p_type[$type].'在线付款',
			);
			$obj = $this->GetModel('trade');
			$id = $obj->NewItem($data);
			DisplayZFB($id, $amount, $data['info'], $web_root['web'].'index.php?action=order.detail&id='.$data['id']);
			return RT_NONE;
			break;
		default:
			$this->assign("msg", $p_type[$type].UN_OPEN);
		}
		return RT_MSG;
	}

	function Create()
	{
		if($this->user->usertype == 2 && $this->user->level == 1)
			return RT_ATTACK;
		if(time(0) - $_SESSION['order_set'] > 900)
		{
			$this->assign("msg", "操作超时，请在15分钟内确认订单");	//否则商品过期导致订单无效
			return RT_MSG;
		}
		unset($_SESSION['order_set']);
		//计算总值
		$cart = $_SESSION['cart'];
		$cnt = 0;
		$c_score = 0;
		$amount = $this->GetAmount($cart, $cnt, $c_score);
		if($cnt != count($cart))
		{
			$this->assign('msg', '部分商品已过期，请修改购物车之后再下单');
			return RT_MSG;
		}

		$userid = $this->user->userid;
		$data = array('userid' => $this->user->userid);
		if($this->params['need_card_birthday'] == 1)
			$data['card1'] = $this->params['card_birthday'];
		if($this->params['need_card'] == 1)
			$data['card2'] = $this->params['card_message'];
		if($this->params['need_album'] == 1)
			$data['attach1'] = 1;
		if($this->params['need_candle'] == 1)
			$data['attach2'] = 1;
		$data['area'] = $this->params['true_area'];
		$data['address'] = $this->params['true_address'];
		$data['consignee'] = $this->params['true_consignee'];
		$data['zipcode'] = $this->params['true_zipcode'];
		$data['mobile_to'] = $this->params['true_mobile_to'];
		$data['mobile_from'] = $this->params['true_mobile_from'];
		$data['sign_building'] = $this->params['true_sign_building'];
		$data['delivery_type'] = $this->params['true_delivery_type'];
		$data['delivery_time'] = $this->params['dely_date'] . " " . $this->params['dely_time'];
		$data['pay_type'] = $this->params['payment'];
		if($this->params['need_inv'] == 1)
		{
			$data['inv_title'] = $this->params['inv_payee'];
			$data['inv_type'] = $this->params['inv_content'];
		}
		$data['message'] = $this->params['postscript'];
		$data['type'] = $this->user->usertype;


		$data['amount_pre'] = $amount;
		$v_data = false;
		//积分和代金券规则
		if($amount == 0)
		{
			$voucher_amount = 0;
			$score_amount = 0;
			$voucher_id = '';
			$score = 0;
			$data['pay_adm'] = 1;
		}
		else
		{
			$voucher_id = $this->params['card_pwd'];	//代金券码
			if($voucher_id != '')
			{
				if(!CheckNo($voucher_id))	//非法序列号
				{
					debug_log('非法序列号'.$voucher_id);
					return RT_ATTACK;
				}
				$msg = '';
				$v_data = $this->GetVoucher($voucher_id, $msg);
				if($v_data == null)
				{
					if($msg == '')
						return RT_ATTACK;
					$this->assign('msg', $msg);
					return RT_MSG;
				}
			}
			$score = $this->params['integral'];			//积分值
			$voucher_amount = 0;						//代金券兑换值
			$score_amount = 0;							//积分兑换值
			$data['amount'] = $this->CountPay($amount,  $v_data, $score, $voucher_amount, $score_amount);
			if($amount != $data['amount'])	//不积分
				$c_score = 0;
			$uobj = $this->GetModel("user");
			if($score > 0 && $uobj->DecScore($this->user->userid, $score) <= 0)	//扣积分
			{
				$this->assign('msg', '积分不足');
				return RT_NONE;
			}
			if($data['amount'] == 0)
				$data['pay_adm'] = 1;
			else if($data['pay_type'] == 1)
			{
				if(!$uobj->DecMoney($this->user->userid, $data['amount']))
				{
					$this->assign('msg', '余额不足');
					return RT_NONE;
				}
				$data['pay_adm'] = 1;
			}
			else
				$data['pay_adm'] = 0;
		}
		//结束结算

		$data['trade_money1'] = $voucher_amount;
		$data['trade_money2'] = $score_amount;
		$data['money1_code'] = $voucher_id;
		$data['money2_code'] = $score;
		$data['add_score'] = $c_score;

		$this->assign('money_infos', array(
			'all' => $amount,
			'pay' => $data['amount'],
			'vchr_id' => $voucher_id,
			'vchr_all' => $v_data ? $v_data['amount'] : 0,
			'vchr_use' => $voucher_amount,
			'score' => $score,
			'score_amount' => $score_amount,
			'score_add' => $c_score,
			'pay_sta' => $data['pay_adm'] != 0,
		));

		$obj = $this->GetModel("Order");
		$id = $obj->Create($data);
		if($id == 0)
		{
			$this->assign("msg", "创建订单失败");
			return RT_MSG;
		}
		$food = $obj->SaveData($id, $cart);
		if($food == 0)
		{
			$this->assign("msg", "存储订单失败");
			return RT_MSG;
		}
		unset($_SESSION['cart']);
		//使用代金券
		if($v_data)
		{
			$vobj = $this->GetModel("Voucher");		//用代金券
			$vobj->UseById($v_data['id'], $voucher_amount, $id, $this->user->userid);
		}
		$this->assign("id", $id);
		return RT_TPL;
	}

	private function GetVoucher($no, &$msg)
	{
		$vobj = $this->GetModel("Voucher");
		$v_data = $vobj->GetInfo($no);
		if(!$v_data)
			return null;
		switch($v_data['status'])
		{
		case 4:	
			$msg = VOUCHER_USE; //已使用
			return null;
		case 5:
			$msg = VOUCHER_OUT; //已使过期
			return null;
		}
		return $v_data;
	}

	private function CountPay($amount,  $v_data, &$score, &$voucher_amount, &$score_amount)
	{
		$new_amount = $amount;
		$obj = $this->GetModel("Voucher");
		$voucher_amount = 0;
		$score_amount = 0;
		if($v_data)
		{
			$val = $v_data['amount'];
			if($val > $amount)
				$val = $amount;
			$voucher_amount = $val;			//代金券实际使用值
			$new_amount -= $val;
		}
		if($new_amount == 0 || $score == 0)	//代金券足够，不再扣积分
		{
			$score = 0;
			return $new_amount;
		}
		$unit = floor($score / 10);
		$score = $unit * 10;
		$score_amount = $unit * 100;
		if($score_amount > $new_amount)
			$score_amount = $new_amount;	//积分实际兑换值
		$new_amount -= $score_amount;
		return $new_amount;
	}

	function AddComment()
	{
		$obj = $this->GetModel("Order");
		$odata = $obj->GetGoodBase($this->user->userid, $this->params['id']);
		if(!$odata)
		{
			echo "1";
			return RT_NONE;
		}
		$data = array(
			'goods_id' => $odata['good_id'],
			'version' => $odata['version'],
			'size' => $odata['size'],
			'user_id' => $this->user->userid,
			'username' => $this->user->username,
			'content' => $this->params['comment'],
			'taste' => $this->params['taste'],
			'service' => $this->params['service'],
			'whole' => $this->params['whole'],
			'visible' => 0,
		);
		$cobj = $this->GetModel("comment");	
		$id = $cobj->AddComment($data);
		if($id <= 0)
		{
			echo "2";
			return RT_NONE;
		}
		$obj->SetCommentId($this->params['id'], $id);
		echo "0";
		return RT_NONE;
	}

	private function GetAmount($cart, &$cnt, &$score)
	{
		//计算总值
		$amount = 0;
		$cnt = 0;
		$score = 0;
		$cart = $_SESSION['cart'];
		foreach($cart as $item)
		{
			if($item['status'] == 0)
			{
				$c_amount =$item['discount'] * $item['price'] * $item['cnt']; 
				$amount += $c_amount;
				$cnt++;
				if($item['discount'] == 1)
					$score += $c_amount;		//仅不折的
			}
		}
		$score = floor($score/100);	//每100积一分
		return round($amount, 2);
	}
}

